#!/usr/bin/env python

from google.appengine.ext import webapp
from models.library import Library
from datetime import datetime, timedelta

# This controller handles the
# generation of the front page.

class ValidateLibsHandler(webapp.RequestHandler):

    def get(self):
        
        limit = self.request.get('limit')
        limit = int(limit) if limit else 10
        
        # minimum period since last test
        delay = timedelta(hours=1)
        
        q = Library.all()
        if self.request.get('problems'):
            q.filter('has_problems', True)
        q.order("tested")
        
        results = q.fetch(limit)
        
        self.response.headers["Content-Type"] = "text/plain"
        for lib in results:
            if lib.tested + delay <= datetime.utcnow():
                problems = lib.validate()
                self.response.out.write("%s: %s" % (lib.name, problems or "OK\n"))
                lib.put()
            else:
                self.response.out.write("%s: skipped (last tested: %s)\n" % (lib.name, str(lib.tested)))
                
